package jwt

import (
	"fmt"

	"github.com/golang-jwt/jwt/v4"
)

func CreateToken(secretKey string, iat, seconds int64, payload int) (string, error) {
	claims := make(jwt.MapClaims)
	claims["exp"] = iat + seconds
	claims["iat"] = iat
	claims["payload"] = payload
	token := jwt.New(jwt.SigningMethodHS256)
	token.Claims = claims
	return token.SignedString([]byte(secretKey))
}

func CheckoutToken(tokenString string) int {
	token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
		// Don't forget to validate the alg is what you expect:
		if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
			return nil, fmt.Errorf("Unexpected signing method: %v", token.Header["alg"])
		}
		// hmacSampleSecret is a []byte containing your secret, e.g. []byte("my_secret_key")
		hmacSampleSecret := []byte(tokenString)
		return hmacSampleSecret, nil
	})
	if err != nil {
		return 0
	}
	claims, _ := token.Claims.(jwt.MapClaims)
	res, _ := claims["payload"].(float64)
	return int(res)
}
